package com.ideyatech.allowancereceipts.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.google.gson.Gson;
import com.ideyatech.allowancereceipts.entity.Employee;
import com.ideyatech.allowancereceipts.entity.Establishment;
import com.ideyatech.allowancereceipts.entity.Receipt;
import com.ideyatech.allowancereceipts.service.EmployeeService;
import com.ideyatech.allowancereceipts.service.EstablishmentService;
import com.ideyatech.allowancereceipts.service.ReceiptService;
import com.ideyatech.allowancereceipts.util.VATUtil;

public class AjaxController extends MultiActionController {

	private static final Gson gson = new Gson();

	private EstablishmentService establishmentService;

	private EmployeeService employeeService;

	private ReceiptService receiptService;

	private List<Receipt> receipts;

	public AjaxController() {
		receipts = new ArrayList<Receipt>();
	}

	public void setEstablishmentService(
			EstablishmentService establishmentService) {
		this.establishmentService = establishmentService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public void setReceiptService(ReceiptService receiptService) {
		this.receiptService = receiptService;
	}

	public void fetchEstablishments(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		List<Establishment> establishments = establishmentService.findAll();
		response.getWriter().write(gson.toJson(establishments));
	}

	public void fetchEmployees(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		List<Employee> employees = employeeService.findAll();
		response.getWriter().write(gson.toJson(employees));
	}

	public void addEmployee(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String employeeJson = request.getParameter("employee");
		Employee employee = gson.fromJson(employeeJson, Employee.class);
		employeeService.save(employee);

		writeJsonSuccessTrue(response);
	}

	public void addEstablishment(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String establishmentJson = request.getParameter("establishment");
		Establishment establishment = gson.fromJson(establishmentJson,
				Establishment.class);
		establishmentService.save(establishment);

		writeJsonSuccessTrue(response);
	}

	public void addReceipt(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String receiptJson = request.getParameter("receipt");
		Receipt receipt = gson.fromJson(receiptJson, Receipt.class);
//		receiptService.save(receipt);
		receipts.add(receipt);
		writeJsonSuccessTrue(response);
	}

	public void receiptsToCsv(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		writeReceiptsTo(response);
	}

	private void writeReceiptsTo(HttpServletResponse response)
			throws IOException {
		response.setContentType("text/csv");
		response.setHeader("Content-Disposition",
				"attachment; fileName=receipts.csv");
		PrintWriter writer = response.getWriter();
		writer.write("\"EMPLOYEE\", \"SUPPLIER'S REGISTERED NAME\","
				+ " \"TIN\", \"ADDRESS\", \"MUNICIPALITY\", \"Gross"
				+ " Purchase\", \"VAT Input\", \"VAT\"\n");
		for (Receipt receipt : receipts) {
			StringBuffer buffer = new StringBuffer();
			buffer.append("\"")
				  .append(receipt.getOwner().getFirstName())
				  .append(" ")
				  .append(receipt.getOwner().getLastName())
				  .append("\", ");
			
			buffer.append("\"")
			  	  .append(receipt.getEstablishment().getName())
			  	  .append("\", ");
			
			buffer.append("\"")
		  	  	  .append(receipt.getEstablishment().getTaxIDNumber())
		  	      .append("\", ");
			
			buffer.append("\"")
	  	  	  	  .append(receipt.getEstablishment().getAddress())
	  	  	  	  .append("\", ");
			
			buffer.append("\"")
		  	  	  .append(receipt.getEstablishment().getMunicipality())
		  	  	  .append("\", ");
			
			buffer.append("\"")
		  	  	  .append(receipt.getGrossPurchase())
		  	  	  .append("\", ");
			
			double vatableAmount = VATUtil.getVatableAmount(Double
					.valueOf(receipt.getGrossPurchase().toString()));
			buffer.append("\"")
		  	  	  .append(new DecimalFormat("#.##").format(vatableAmount))
		  	  	  .append("\", ");
			
			double vat = VATUtil.getVat(Double.valueOf(receipt.getGrossPurchase().toString()));
			buffer.append("\"")
		  	  	  .append(new DecimalFormat("#.##").format(vat))
		  	  	  .append("\"\n");
			
			writer.append(buffer.toString());
		}
	}

	private void writeJsonSuccessTrue(HttpServletResponse response)
			throws IOException {
		response.setContentType("application/json");
		response.getWriter().write(gson.toJson(true));
	}

}
